<?php

namespace App\Logic;

use Common\Model\MessageModel;

class MessageLogic extends MessageModel
{	
	// 存放外部接口返回信息
	public $msg = '请求成功';
	
	// 存储未加工验证码、短信内容
	public $content = '';
	
	public $tplStr = '【签约提醒】';
	
	public $headers = array(
			'Content-Type'=>'application/x-www-form-urlencoded',
			'charset'=>'utf-8',
	);
	
	private $option = array(
			'gateway' => "http://sdk.entinfo.cn:8061/webservice.asmx/mdsmssend",
			'sn' => "SDK-WSS-010-10407",
			'pwd' => "1aad)2)c-96",
			'rrid' => '', //唯一标识，数字
			'msgfmt' => '', //内容编码
			'ext' => '4', // 拓展子号
			'stime' => '', // 定时时间
	);
	
	protected function _initialize()
	{
		parent::_initialize();
	}
	
	public function setRequestData($request = array())
	{
		if( empty($request) )
		{
			return false;
		}
	
		if( empty($request['mobile']) === false )
		{
			// 简单验证手机号格式
			if( preg_match('/^1([0-9]{9})/',$request['mobile']) == false )
			{
				$this->error = '手机号不合法';
	
				return false;
			}
		}
		else
		{
			$this->error = '手机号不能为空';
	
			return false;
		}
	
		if( empty($request['template']) )
		{
			// 默认template为code
			$request['template'] = 'code';
		}
	
		$this->content = $request['content'];
	
		switch ($request['template'])
		{
			case 'code':
				if( empty($request['content']) === false )
				{
					$content = $request['content'];
				}
				else
				{
					$content = generate_string(4,$chars = '0123456789');
				}
	
				$this->content = $content;
				$request['content'] = sprintf('%s您的验证码是：%s。请不要把验证码泄露给其他人。', $this->tplStr,$content);
	
				break;
					
			case 'text':
				if( empty($request['content']) )
				{
					$this->error = '请填写自定义短信内容';
	
					return false;
				}
				else
				{
					$request['content'] = sprintf('%s%s',$this->tplStr ,$request['content']);
				}
	
				break;
					
			default:
				$this->error = '不支持的template类型';
				
				return false;
				break;
		}
	
		unset($request['sign']);
		
		return $request;
	}
	
	public function saveRequestData($data = array())
	{
		$data['create_time'] = date('Y-m-d H:i:s',time());
		$data['state'] = 'INIT';
		
		$data = $this->create($data);
		
		if( $data === false )
		{
			return false;
		}
		
		if( $this->updateRecord($data) === false )
		{
			return false;
		}
		
		return $data;
	}
	
	public function curlPost($request = array())
	{
		$request = $this->getPostData($request);
		
		$curl = new \Org\Net\Http\Curl();
		
		$this->headers['Content-Length'] = strlen(http_build_query($request));
		
		$curl->setHeaders($this->headers);
		
		$result = $curl->post($this->option['gateway'],$request);
		
		if( $curl->error )
		{
			$this->error = $curl->errorMessage;
			
			return false;
		}
		
		return $result->asXML();
	}
	
	public function saveResponseData($resultStr = '',$data = array())
	{
		$resultArr = $this->xmlToArray($resultStr);
		
		if( is_array($resultArr) === false )
		{
			$this->error = '接口返回参数格式错误';
		
			return false;
		}
		
		// 更新短信验证数据、发送完成时间
		$updateData = array();
		$updateData['raw'] = $resultStr;
		$updateData['time'] = date('Y-m-d H:i:s',time());
		
		if( strpos($resultArr[0],'-') === false )
		{
			$this->msg = '短信发送成功';
			
			$updateData['state'] = 'SUCCESS';
		}
		else
		{
			$this->msg = sprintf('短信发送失败，错误编码:%s', $resultArr[0]);
			
			$updateData['state'] = 'FAIL';
		}
		
		$updateData = $this->create($updateData);
		if( $updateData === false )
		{
			return false;
		}
		
		if( $this->updateRecordByParm($data,$updateData) === false )
		{
			return false;
		}
		
		$updateData['message_content'] = $this->content;
		
		return array_merge($data,$updateData);
	}
	
	protected function getPostData($request = array())
	{
		unset($request['template']);
		unset($request['timestamp']);
		
		$request['pwd'] = strtoupper(md5($this->option['sn'] . $this->option['pwd']));
		
		return array_merge($this->option,$request);
	}
	
	protected function xmlToArray($raws)
	{
		libxml_disable_entity_loader(true);
	
		$data = json_decode(json_encode(simplexml_load_string($raws, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	
		return $data;
	}
	
	public function checkRequire($required = array(),$query = array())
	{
		$diff = array_diff($required,array_keys($query));
	
		if( empty($diff) === false )
		{
			foreach ($diff as $row)
			{
				$this->error .= $row . '不能为空,';
			}
			$this->error = trim($this->error,',');
				
			return false;
		}
		return true;
	}
	
	public function getSecretKey()
	{
		return '72969e04baa8b6e43fae34e1969d56a6';
	}
	
	public function checkSign($data = array())
	{
		$clientSign = $data['sign'];
		
		unset($data['sign']);
		
		$key = $this->getSecretKey();
		
		$sign = $this->getSign($data,'md5',$key);
		
		return $clientSign === $sign;
	}
	
	public function getSign($data = array(),$salt = 'md5,strtolower',$key='')
	{
		ksort($data);

		$string = '';
		
		foreach($data as $k=>$item)
		{
			if( $item != "" )
			{
				$string .= $k.'='.$item.'&';
			}
		}
	
		$string = rtrim($string, "&").$key;
		
		foreach (explode(',', $salt) as $item)
		{
			$sign = $item($string);
		}
		
		return $sign;
	}
		
}
